﻿function SimpleSlideshow(items, transition, options){
    for(var option in options) this[option] = options[option];
    this.items = items;
    this.transition = transition;
    
    this._queue = [];
    
    if(this.autoplay)
        this.play();
}

SimpleSlideshow.prototype = {
    delay: 7000,
    circular: true,
    autoplay: false,
    
    _currentIndex: 0,
    _autoplayTicker: null,
    _transiting: false,
    _queue: null,
    
    show: function(index){
        var self = this;
        this._queue.push(index);
        
        if(!this._transiting){
            (function(nextIndex){
                var callee = arguments.callee;
                var previous, next;
                
                if(nextIndex !== self._currentIndex){
                    previous = self.current();
                    next = { index: nextIndex, element: self.items[nextIndex] };
                    
                    if(typeof self.onshow === "function"){
                        var result = self.onshow({previous: previous, next: next});
                        
                        if(typeof result === "boolean" && !result)
                            return;
                    }
                    
                    self._transiting = true;
                    self.pause();
                    
                    self.transition(next, previous, function(){
                        self._transiting = false;
                        self._currentIndex = nextIndex;
                        
                        if(self.autoplay) 
                            self.play();
                        
                        if(self._queue.length)
                            callee(self._queue.shift());
                    });
                }else if(self._queue.length){
                    callee(self._queue.shift());
                }
            })(this._queue.shift());   
        }
    },
    
    play: function(){
        var self = this;
        
        clearInterval(this._autoplayTicker);
        this._autoplayTicker = setInterval(function(){
            var next = self.current().index + 1, 
                length = self.items.length;
            
            if(!self.circular && (next < 0 || next >= length)){
                self.pause();
                return;
            }
            
            self.show(next % length);
        }, this.delay);
    },
    
    pause: function(){
        clearInterval(self._autoplayTicker);
    },
    
    current: function(){
        return { 
            index: this._currentIndex,
            element: this.items[this._currentIndex] 
        };
    }
};